const router = require("koa-router")();
const HouseModel = require("../models/house.js");
const RoomModel = require("../models/room.js");
const ResultHelper = require("../utils/resultHelper.js");
const VerifyHelper = require("../utils/verifyHelper.js");
const formatDateHelper = require('../utils/formatDateHelper.js')


router.post("/house", async ctx => {
	VerifyHelper.token(ctx)
	const {
		id,
		name,
		create,
		modify
	} = ctx.request.body;

	if (!name) {
		return ResultHelper.errInfo422(ctx, "请填写单元名")
	}

	if (!id) {
		const nameTrue = await HouseModel.findOne({
			name: ctx.request.body.name
		});
		if (nameTrue) {
			return ResultHelper.errInfo422(ctx, "单元名已存在")
		}
		const housePost = new HouseModel({
			id,
			name,
			create,
			modify
		});
		const res = await housePost.save();
		ctx.body = {
			code: 200,
			msg: "添加成功"
		}
	} else {
		// 已存在数据
		// 获取下数据的内容
		const item = await HouseModel.findOne({
			id: ctx.request.body.id
		});
		const res = await HouseModel.updateOne({
			id: id
		}, {
			$set: {
				id,
				name: ctx.request.body.name ? ctx.request.body.name : item.name,
				create: ctx.request.body.create ? ctx.request.body.create : item.create,
				modify: formatDateHelper.date()
			}
		});
		ctx.body = {
			code: 200,
			msg: "编辑成功"
		}
	}
})

router.get("/houses", async ctx => {
	let {
		page,
		limit,
		name,
		id
	} = ctx.query;
	if (page == undefined) {
		page = 0
	}
	if (limit == undefined) {
		limit = 10
	}
	const query = {};

	// 构建查询条件
	if (name) {
		query.name = {
			$regex: ctx.query.name
		}; // 不区分大小写的正则表达式
	}

	if (id !== '0') {
		query.id = id;
	}

	var data = await HouseModel.find(query).skip(Number(page - 1) * limit).limit(Number(limit));
	var total = await HouseModel.find(query).countDocuments();
	//  为每个单元楼添加对应的 room的总数
	const enhancedData = await Promise.all(data.map(async house => {
		const rooms = await RoomModel.find({
			house_id: house.id
		});
		return {
			...house.toObject(),
			rooms
		};
	}));
	ctx.body = {
		code: 200,
		data: enhancedData,
		total,
		msg: "ok"
	}

})

router.get("/del/house", async ctx => {
	VerifyHelper.token(ctx)
	const {
		id
	} = ctx.request.query;
	let res = await HouseModel.deleteOne({
		id: id
	});
	ctx.body = {
		code: 200,
		msg: '删除成功'
	}
})


module.exports = router;